//
//  GSDKCommonMethod.m
//  GameSDK
//
//  Created by Johnny on 2017/7/28.
//  Copyright © 2017年 Johnny. All rights reserved.
//

#import "GSDKCommonMethod.h"
#import "GSDKKeyChainHelper.h"
#import <AdSupport/AdSupport.h>
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <sys/sysctl.h>
#import "YYKit.h"
#import "GSDKServicesManager.h"

static GSDKCommonMethod * shared = nil;
@interface GSDKCommonMethod() {
    UIDeviceOrientation orientation;
}
@end

@implementation GSDKCommonMethod
+ (GSDKCommonMethod *)shared {
    static dispatch_once_t pred;
    dispatch_once(&pred,^{
        if (shared == nil) {
            shared = [[self alloc]init];
            shared.GSDKCid = [[NSBundle mainBundle] infoDictionary][@"channelID"];
            shared.GSDKType = @"2";
        }
    });
    return shared;
}

+ (int)returnOrientation {
    return (int)[[UIApplication sharedApplication] statusBarOrientation];
}

+ (CGFloat )getHight {
    if (IS_VERSION_IOS7) {
        return windowHeight;
    }
    CGFloat height = 0;
    if (windowWidth < windowHeight) {
        height = windowWidth;
    } else {
        height = windowHeight;
    }
    return height;
}

+ (CGFloat )getWidth {
    if (IS_VERSION_IOS7) {
        return windowWidth;
    }
    CGFloat width = 0;
    if (windowWidth > windowHeight) {
        width = windowWidth;
    } else {
        width = windowHeight;
    }
    return width;
}

+ (void)saveDeviceID:(NSString *)deviceID {
    [GSDKKeyChainHelper saveValue:deviceID withKey:deviceIDKey];
}

+ (NSString *)getDeviceID {
    NSString * deviceID = [GSDKKeyChainHelper getValueIn:deviceIDKey];
    if (deviceID == nil) {
        NSString *ip =  [GSDKCommonMethod getIPAddress];
        NSString *model = [GSDKCommonMethod getCurrentDeviceModel];
        NSString *version = [[UIDevice currentDevice] systemVersion];
        NSInteger num = arc4random() % 1000000;
        NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss:SSS"];
        NSString *date =  [formatter stringFromDate:[NSDate date]];
        NSString *timeLocal = [[NSString alloc] initWithFormat:@"G%@%ld%@%@%@", date, num, ip, model, version];
        deviceID = timeLocal.md5String;
        [GSDKCommonMethod saveDeviceID:deviceID];
    }
    return [GSDKKeyChainHelper getValueIn:deviceIDKey];
}

+ (NSString *)getDeviceMSG {
    NSString *ip =  [GSDKCommonMethod getIPAddress]; //ip地址
    NSString *model = [GSDKCommonMethod getCurrentDeviceModel];//手机型号
    NSString *version = [[UIDevice currentDevice] systemVersion]; //系统版本
    NSString *resolution = [NSString stringWithFormat:@"%.0f*%.0f",[GSDKCommonMethod getWidth],[GSDKCommonMethod getHight]];
    NSString *language = [NSString stringWithFormat:@"%u", GSDKCOMMONMETHOD.language];
    DEBUGMSG(@"[GSDKCommonMethod getDeviceID] = %@", [GSDKCommonMethod getDeviceID]);
    //FIXME: 把ver和ver_name替换掉
    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:@{@"phone_ip": ip,
                                                                  @"phone_model": model,
                                                                  @"phone_version": version,
                                                                  @"phone_resolution": resolution,
                                                                  @"idfa": [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString],
                                                                  @"ver": [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"],
                                                                  @"ver_name": [[NSBundle mainBundle] infoDictionary][@"CFBundleVersion"],
                                                                  @"language": language}
                                                                    options:0
                                                                  error:nil];
    NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return myString;
}

+ (NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while (temp_addr != NULL) {
            if( temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    
    // Free memory
    freeifaddrs(interfaces);
    
    return address;
}

+ (NSString *)getCurrentDeviceModel {
    int mib[2];
    size_t len;
    char *machine;
    
    mib[0] = CTL_HW;
    mib[1] = HW_MACHINE;
    sysctl(mib, 2, NULL, &len, NULL, 0);
    machine = malloc(len);
    sysctl(mib, 2, machine, &len, NULL, 0);
    
    NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
    free(machine);
    return platform;
}

- (void)online {
    __weak GSDKCommonMethod * bSelf = self;
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:60 block:^(NSTimer * _Nonnull timer) {
        if (bSelf.game_ext != nil && bSelf.accountModel != nil) {
            NSMutableDictionary * dic = [bSelf.game_ext mutableCopy];
            dic[@"date"] = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
            GSDKGameOnlineTimeModel * model = [[GSDKGameOnlineTimeModel alloc] initWithToken:bSelf.GSDKToken andGameOnlineTime:[dic modelToJSONString]];
            [[GSDKServicesManager new] oneTimeRequest:model andCompletionBlock:nil];
        }
    } repeats:true];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}

/**
 *  签名加密
 *
 *  @param keyString 加密字符串
 *
 *  @return 、加密后
 */
- (NSString *)generateSignKey:(NSString *) keyString {
    if (keyString) {
        NSString * signKey = [keyString stringByAppendingFormat:@"%@",GSDKINITCONFIGURE.appKey];
        signKey = signKey.md5String;
        return signKey;
    }
    return nil;
}

@end
